<?php
require_once "xpface/util/data/IDataSource.iface.php";

abstract class DataSourceFactory {
    public static function getData($source) {
        $source = self::parseSource($source);
        switch ($source["prefix"]) {
            case "json":
            {
                $className = "JsonDataSource";
                if (!class_exists($className)) {
                    require_once "xpface/util/data/adapters/{$className}.class.php";
                }
                break;
            }
            case "cache":
            {
                $className = "CacheDataSource";
                if (!class_exists($className)) {
                    require_once "xpface/util/data/adapters/{$className}.class.php";
                }
                break;
            }
            case "file":
            {
                $className = "FileDataSource";
                if (!class_exists($className)) {
                    require_once "xpface/util/data/adapters/{$className}.class.php";
                }
                break;
            }
            case "http":
            {
                $className = "HttpDataSource";
                if (!class_exists($className)) {
                    require_once "xpface/util/data/adapters/{$className}.class.php";
                }
                break;
            }
            case "string":
            {
                $className = "StringDataSource";
                if (!class_exists($className)) {
                    require_once "xpface/util/data/adapters/{$className}.class.php";
                }
                break;
            }
            default:
            {
                $className = "StringDataSource";
                if (!class_exists($className)) {
                    require_once "xpface/util/data/adapters/{$className}.class.php";
                }
                break;
            }
        }
        
        $obj = new ${className}();
        return $obj->getData($source["data"], $source["format"]);
    }
    public static function parseSource($source) {
        //1 2 3
        $returnArray = array();
        $pattern = "/([a-z]*?)\+?([a-z]*?)\:(.*)/";
        preg_match($pattern, $source, $matches);
        //var_dump($matches);
        if (!trim($matches[2])) {
            $returnArray["prefix"] = $matches[2];
        } else {
            $returnArray["prefix"] = $matches[1];
            $returnArray["format"] = $matches[2];
        }
        $returnArray["data"] = $matches[3];
        return $returnArray;
    }
}
